<?php

class FileUpload
{
    private $PATH = "./file";
    private $userId = 0;
    private $userManager;

    public function __construct(UserManager $userManager)
    {
        $this->userManager = $userManager;
        $this->userId = $userManager->getCurrentId();
    }

    public function uploadIcon($file)
    {
        $newFilePath = "$this->PATH/user_$this->userId" . "icon.png";
        $isUpload = move_uploaded_file($file["tmp_name"], $newFilePath);
        if ($isUpload) {
            $arr = array();
            $arr["head_icon"] = "true";
            return $this->userManager->alterUser($this->userId, $arr);
        }
        return "error";
    }

    public function upload($file, $extend)
    {
        $this->checkFileLegal($file["name"], $extend);
        $newFilePath = "$this->PATH/user_$this->userId" . "_" . $file["name"];
        $isUpload = move_uploaded_file($file["tmp_name"], $newFilePath);
        if ($isUpload) {
            $arr = array();
            $userData = $this->userManager->getUser();
            $arr["files"] = json_decode($userData[0]["files"], true);
            $arr["files"][] = $newFilePath;
            $arr["files"] = json_encode($arr["files"]);
            return $this->userManager->alterUser($this->userId, $arr);
        }
        return "error";
    }

    public function removeFile($fid)
    {
        $arr = array();
        $userData = $this->userManager->getUser();
        $arr["files"] = json_decode($userData[0]["files"], true);
        unset($arr["files"][$fid]);
        $arr["files"] = json_encode(array_values($arr["files"]));
        return $this->userManager->alterUser($this->userId, $arr);
    }

    private function checkFileLegal($fileName, $extend)
    {
        if (!in_array(pathinfo($fileName, PATHINFO_EXTENSION), $extend)) {
            die("File type error");
        }
        /*foreach ($extend as $v) {
            if (pathinfo($file, PATHINFO_EXTENSION) == $v) {
                die("File type error");
                break;
            }
        }*/
    }
}